package br.edu.ufersa.scrumgame.util;

import java.io.File;
import java.io.FileOutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;

public class Util {

	public static String hashMD5Hex(String texto) throws NoSuchAlgorithmException {
		
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(texto.getBytes());
		byte[] digest = md.digest();
		StringBuffer sb = new StringBuffer();
		for (byte b : digest) {
			sb.append(Integer.toHexString((int) (b & 0xff)));
		}

		return sb.toString();
		
	}
	
	public static void addMessage(String msg) {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		FacesMessage message = new FacesMessage(null, msg);
		facesContext.addMessage(null, message);
	}
	
	public static void createFoto(String nomeArquivo, byte[] foto) {
		try {
			ServletContext sContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
					.getContext();
			File folder = new File(sContext.getRealPath("/temp"));
			if (!folder.exists()) {
				folder.mkdir();
			}

			String arquivo = sContext.getRealPath("/temp") + File.separator + nomeArquivo + ".jpg";

			FileOutputStream fos;

			try {
				fos = new FileOutputStream(arquivo);
				fos.write(foto);

				fos.flush();
				fos.close();
			} catch (Exception e) {
				e.printStackTrace();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
